import { StackActions, NavigationActions } from 'react-navigation'

let _navigator

function setTopLevelNavigator (navigatorRef) {
  _navigator = navigatorRef
}

function navigate (routeName, params, action = {}, key) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
      action: action
    })
  )
}
function pop (n) {
  _navigator.dispatch(
    StackActions.pop({n})
  )
}
function push (routeName, params) {
  _navigator.dispatch(
    StackActions.push({
      routeName,
      params
    })
  )
}
function goBack () {
  _navigator.dispatch(
    NavigationActions.back()
  )
}
function replace (routeName, params, action = {}) {
  _navigator.dispatch(
    StackActions.replace({
      routeName,
      params,
      action
    })
  )
}
function reset (routeName, params) {
  const resetAction = StackActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({ routeName: routeName, params })]
  })
  _navigator.dispatch(resetAction)
}


function resetToPage(routeName,params={}) {
  const resetAction = StackActions.reset({
    index: 0,
    actions: [
      NavigationActions.navigate({
        routeName,
        params
      })
    ]
  });
  _navigator.dispatch(resetAction);
}

/**
 * 跳转登陆页
 */
function resetToLoginPage() {
  if(_navigator.state.nav.routes[0].routeName!="Login")
  {
    const resetAction = StackActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({
          routeName: "Login",
          params: {},
        }),
      ],
    });
    _navigator.dispatch(resetAction);
  }
}

/**
 * 跳转维护页
 */
function resetToMaintainPage( info = null) {
  const resetAction = StackActions.reset({
    index: 0,
    actions: [
      NavigationActions.navigate({
        routeName: "Maintain",
        params: { info }
      })
    ]
  });
  _navigator.dispatch(resetAction);
}

export const getNavigator = () => {
  return _navigator
}

// add other navigation functions that you need and export them

export default {
  navigate,
  replace,
  reset,
  setTopLevelNavigator,
  push,
  pop,
  goBack,
  resetToPage,
  resetToLoginPage,
  resetToMaintainPage
}
